<template>
	<n-number-animation
		ref="numberAnimationInstRef"
		:from="currentValue"
		:to="newValue"
		:duration="Number(duration)"
		:precision="Number(_precision)"
		show-separator></n-number-animation>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue'
import { NNumberAnimation } from 'naive-ui'
import { fmtAmount } from '@/utils'

const props = defineProps({
	to: [Number, String],
	from: {
		type: [Number, String],
		default: 0
	},
	duration: {
		type: [Number, String],
		default: 500
	},
	precision: {
		type: [Number, String],
		default: 0
	}
})

const numberAnimationInstRef: any = ref(null)
const _precision = computed(() => {
	const fmtArr = fmtAmount(props.to).split('.')
	if (fmtArr.length > 1) {
		return fmtArr[1].length
	}
	return 0
})
const currentValue = ref(0)
const newValue = ref(0)

watch(
	() => props.to,
	(newVal, oldVal) => {
		currentValue.value = Number(oldVal) || 0
		newValue.value = Number(newVal)
	},
	{ immediate: true }
)

onMounted(() => {
	numberAnimationInstRef.value?.play()
})
</script>

<style scoped></style>
